import {ref} from "vue"
import createSocket from "@/utils/socket"
export function useWebSocket(){
  const websocket=ref()
  const store = useStore()
  const initWebSocket=()=>{
    const token=store.state.user.token
    if(window.VUE_APP_URL[import.meta.env.MODE].messageWsUrl){
      //初始化
      websocket.value=createSocket({
      url:`${window.VUE_APP_URL[import.meta.env.MODE].messageWsUrl}/${encodeURIComponent(token)}`,
      name:"",
      isHeart:true,
      isReconnection:true,
      received:getNoticeData
      })
      
      //建立链接
      websocket.value.connect()
      store.commit('notice/setWs',null)  
      store.commit('notice/setWs',websocket.value)  
    }
  }
  //关闭
  const close=async ()=>{
    if(store.state.notice.websocket?.close){
     await store.state.notice.websocket?.close()
    }
    clearNotice()
    store.commit('notice/setWs',null)
  }
  //获取消息
  const getNoticeData=(data:any)=>{
    if(data){
      console.log("消息--websocket",data);
      store.commit('notice/setNoticeList',{type:'add',msg:JSON.parse(data)})
    }
  }
  //移除指定索引的消息
  const clearNoticeItem=(index:number,item?:object)=>{
    store.commit('notice/setNoticeList',{type:'remove',index:index,msg:item})
  }
  
  //移除消息列表数据
  const clearNotice=()=>{
    let t=setTimeout(()=>{
      clearTimeout(t)
      store.commit('notice/setNoticeList',{type:'clear'})
    },500)
  }
  return {
    initWebSocket,
    close,
    getNoticeData,
    clearNotice,
    clearNoticeItem
  }
}